/*
 * Proto Streamer
 * Copyright (C) 2009 John Pritchard.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301 USA.
 */
package p.s.m;

import p.s.Request;
import p.s.Output;

import com.google.protobuf.CodedInputStream;
import com.google.protobuf.Message;

import java.io.IOException;

/**
 * Application uplink.
 * 
 * @see Session
 * @author jdp
 */
public abstract class Post
    extends Session
    implements Producer
{

    public Post(){
        super();
    }

    public final Object getProducerIdentity(){
        return this.methodIdentifier;
    }

    protected abstract void muxEnter(CodedInputStream in)
        throws IOException;

    protected abstract void muxExit();

    protected abstract Message muxRead(CodedInputStream in)
        throws IOException;

    public final void tail(Request request, Output out)
        throws IOException
    {
        Service session = this.setService(request.getPath());
        CodedInputStream cin = CodedInputStream.newInstance(request.getInput());
        try {
            this.muxEnter(cin);

            while (this.open){

                Message m = this.muxRead(cin);

                synchronized(this.sessionMonitor){
                    session = this.session;
                }
                session.update(this,m);

                request.classLoaderMark();
            }
        }
        finally {
            this.muxExit();
        }
    }
    protected final void enter(Service session){
        this.session = session;
        session.enterProducer(this);
    }
    protected final void exit(Service session){
        this.session = null;
        session.exitProducer(this);
    }

}
